import React, { useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';

/**
 * 科技感背景组件 - 提供服务器机房3D场景的背景
 * @param size 背景球的大小，默认为100
 * @param color 背景颜色，默认为深灰色
 * @param lineColor 线条颜色
 * @param glowColor 发光颜色
 * @param lineDensity 线条密度
 */
interface TechBackgroundProps {
  size?: number;
  color?: string;
  lineColor?: string;
  glowColor?: string;
  lineDensity?: number;
}

const TechBackground: React.FC<TechBackgroundProps> = ({
  size = 100, // 大型背景，足够包围整个场景
  color = '#020512', // 与地板一致的深色基底
  lineColor = '#00f0ff', // 与地板一致的亮蓝色线条
  glowColor = '#00f0ff', // 与地板一致的亮蓝色发光效果
  lineDensity = 30 // 线条密度
}) => {
  const meshRef = useRef<THREE.Mesh>(null);
  const timeRef = useRef(0);

  // 自定义背景着色器配置 - 参考地板组件的着色方案
  const shaderConfig = {
    vertexShader: `
      varying vec2 vUv;
      varying vec3 vViewDir;
      void main() {
        vUv = uv;
        vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
        vViewDir = normalize(-mvPosition.xyz);
        gl_Position = projectionMatrix * mvPosition;
      }
    `,
    fragmentShader: `
      uniform float time;
      uniform vec3 color;
      uniform vec3 lineColor;
      uniform vec3 glowColor;
      uniform float lineDensity;
      varying vec2 vUv;
      varying vec3 vViewDir;
      
      // 噪声函数
      float noise(vec2 p) {
        return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453);
      }
      
      // 平滑噪声 - 参考地板组件
      float smoothNoise(vec2 p) {
        vec2 i = floor(p);
        vec2 f = fract(p);
        
        float a = noise(i);
        float b = noise(i + vec2(1.0, 0.0));
        float c = noise(i + vec2(0.0, 1.0));
        float d = noise(i + vec2(1.0, 1.0));
        
        vec2 u = f * f * (3.0 - 2.0 * f);
        
        return mix(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.x * u.y;
      }
      
      // 平铺效果函数 - 创建方块平铺图案
      vec3 createTileEffect(vec2 uv) {
        // 定义平铺大小
        float tileSize = 8.0;
        // 计算平铺坐标
        vec2 tileUV = fract(uv * tileSize);
        vec2 tilePos = floor(uv * tileSize);
        
        // 添加一些随机性，使每个平铺略有不同
        float tileRandom = noise(tilePos);
        
        // 创建方块边缘效果
        float edge = 0.01;
        float border = max(
          step(edge, tileUV.x) * step(edge, 1.0 - tileUV.x),
          step(edge, tileUV.y) * step(edge, 1.0 - tileUV.y)
        );
        
        // 创建内部细节
        float innerDetail = 0.5 + 0.5 * sin(tileRandom * 10.0 + time * 0.2);
        
        // 计算平铺的发光效果
        float tileGlow = 0.05 * (0.5 + 0.5 * sin(tileRandom * 2.0 + time));
        
        // 组合平铺效果
        vec3 tileColor = lineColor * (1.0 - border) * 0.3;
        tileColor += lineColor * tileGlow;
        tileColor += lineColor * innerDetail * 0.1;
        
        return tileColor;
      }
      
      void main() {
        // 基础颜色 - 保持与地板一致的深色基底
        vec3 baseColor = color;
        
        // 添加微妙的渐变效果，增强空间感
        float gradient = 0.2 * vViewDir.z + 0.8;
        baseColor = mix(baseColor, vec3(0.0, 0.0, 0.05), 1.0 - gradient);
        
        // 添加主要网格线 - 参考地板组件的效果，但更微妙
        float lineThickness = 0.008;
        float xLine = step(lineThickness, mod(vUv.x * lineDensity + time * 0.01, 1.0));
        float yLine = step(lineThickness, mod(vUv.y * lineDensity + time * 0.01, 1.0));
        
        // 混合网格线 - 与地板组件类似
        vec3 lineColorMixed = lineColor;
        vec3 mixed = mix(lineColorMixed, baseColor, xLine * yLine);
        
        // 添加动态发光效果 - 参考地板组件的效果
        float glowFactor = 0.15 + 0.1 * sin(time * 0.3 + vUv.x * 5.0 + vUv.y * 5.0);
        vec3 glow = glowColor * glowFactor;
        mixed += glow;
        
        // 添加网格线交点发光效果
        float intersectionGlow = 0.2 * exp(-pow(max(xLine, yLine) - 0.5, 2.0) * 30.0);
        mixed += intersectionGlow * glowColor;
        
        // 添加细微的纹理变化
        float textureNoise = smoothNoise(vUv * 20.0 + time * 0.02) * 0.05;
        mixed += textureNoise;
        
        // 添加区域发光效果 - 模拟背景分区
        float areaGlow = 0.1 * (sin(vUv.x * 3.0) * sin(vUv.y * 3.0)) * exp(-pow(vUv.x - 0.5, 2.0) * 1.0 - pow(vUv.y - 0.5, 2.0) * 1.0);
        mixed += areaGlow * glowColor;
        
        // 添加平铺效果
        vec3 tileEffect = createTileEffect(vUv * 5.0);
        mixed += tileEffect;
        
        // 确保整体亮度适中
        mixed = clamp(mixed, vec3(0.0), vec3(1.0));
        
        gl_FragColor = vec4(mixed, 1.0);
      }
    `,
    uniforms: {
      time: { value: 0 },
      color: { value: new THREE.Color(color) },
      lineColor: { value: new THREE.Color(lineColor) },
      glowColor: { value: new THREE.Color(glowColor) },
      lineDensity: { value: lineDensity }
    },
    side: THREE.BackSide, // 背面渲染，这样从内部看就是背景
    transparent: false
  };

  // 简化的useFrame更新，保持轻微动画效果
  useFrame(() => {
    if (meshRef.current && meshRef.current.material) {
      const material = meshRef.current.material as THREE.ShaderMaterial;
      if ('uniforms' in material && material.uniforms.time) {
        timeRef.current += 0.001;
        material.uniforms.time.value = timeRef.current;
      }
    }
  });

  return (
    <mesh ref={meshRef} position={[0, 0, 0]}>
      <sphereGeometry args={[size, 64, 64]} />
      <shaderMaterial
        vertexShader={shaderConfig.vertexShader}
        fragmentShader={shaderConfig.fragmentShader}
        uniforms={shaderConfig.uniforms}
        side={shaderConfig.side}
        transparent={shaderConfig.transparent}
      />
    </mesh>
  );
};

export default TechBackground;